package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.dingreading.cloud.admin.entity.Course;
import com.dingreading.cloud.admin.entity.CourseTypes;
import com.dingreading.cloud.admin.service.CourseService;
import com.dingreading.cloud.admin.service.CourseTypesService;
import com.dingreading.cloud.admin.service.CourseVideoService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.DescribeException;
import com.dingreading.cloud.common.util.PageBeanDto;
import com.dingreading.cloud.common.util.PageUtil;
import com.dingreading.cloud.common.util.aliyun.OSSClientUtil;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RefreshScope
@RestController
@RequestMapping("/system/course/v2")
@Api(tags = "总部-学院活动管理")
public class CourseControllerV2 {

    @Value("${envi}")
    private String envi;

    @Resource
    private CourseService courseService;
    @Resource
    private CourseTypesService courseTypesService;
    @Resource
    private CourseVideoService courseVideoService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "活动名") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "主分类id") @RequestParam(value = "mainTypeId", required = false) Long mainTypeId,
            @ApiParam(value = "关联分类id") @RequestParam(value = "typeId", required = false) Long typeId,
            @ApiParam(value = "启用状态 1.启用 0.禁用") @RequestParam(value = "enabled", required = false) Integer enabled,
            @ApiParam(value = "是否热门 1.是 0.不是") @RequestParam(value = "hotStatus", required = false) Integer hotStatus
    ) {
        Page<Course> page = this.courseService.pageList(pageUtil, mainTypeId, typeId, keyword, enabled, hotStatus);

        PageBeanDto data = new PageBeanDto();
        data.setTotal(page.getTotalRow());
        data.setList(page.getRecords());
        return R.ok(data);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "新增/修改")
    @PostMapping(value = "/newBean")
    public R<Object> newBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "活动名称") @RequestParam(value = "name") String name,
            @ApiParam(value = "介绍内容") @RequestParam(value = "intro", required = false) String intro,
            @ApiParam(value = "主分类id") @RequestParam(value = "mainTypeId", required = false) Long mainTypeId,
            @ApiParam(value = "关联分类id") @RequestParam(value = "typeId") Long typeId,
            @ApiParam(value = "合作类型") @RequestParam(value = "cooperationType") String cooperationType,
            @ApiParam(value = "运营类型") @RequestParam(value = "operationType") String operationType,
            @ApiParam(value = "角色类型") @RequestParam(value = "role") String role,
            @ApiParam(value = "是否免费 0.不 1.免费") @RequestParam(value = "freeStatus") Integer freeStatus
    ) {
        if (id == null || id <= 0) {
            // 新增
            CourseTypes mainType = courseTypesService.getById(mainTypeId);
            if (mainType == null) return R.fail("主分类获取失败");
            CourseTypes courseTypes = courseTypesService.getById(typeId);
            if (courseTypes == null) return R.fail("关联分类获取失败");
            if (!courseTypes.getLevelEnd().equals(1)) return R.fail("分类不是最后一层不能新增");

            // 获取最大的序号
            int maxOrderNum = courseService.getMaxShowOrder(typeId);

            Course data = new Course();
            data.setName(name);
            data.setIntro(intro);
            data.setMainTypeId(mainTypeId);
            data.setMainTypeName(mainType.getCourseTypeName());
            data.setTypeId(typeId);
            data.setTypeName(courseTypes.getCourseTypeName());
            setTypes(data, cooperationType, operationType, role);
            data.setType(mainType.getType());
            data.setOrderNum(maxOrderNum + 1);
            data.setFreeStatus(freeStatus);
            data.setDownloadNum(0);
            data.setEnabled(1);
            courseService.saveOrUpdate(data);
        } else {
            // 修改
            Course data = courseService.getById(id);
            if (data == null) return R.fail("获取失败");

            if (name != null)
                data.setName(name);
            if (intro != null)
                data.setIntro(intro);
            setTypes(data, cooperationType, operationType, role);
            data.setFreeStatus(freeStatus);
            courseService.saveOrUpdate(data);
        }

        return R.ok();
    }

    private void setTypes(Course data, String cooperationType, String operationType, String role) {
        if (StringUtils.isNotBlank(cooperationType)) {
            List<Integer> array = JSONArray.parseArray(cooperationType, Integer.class);
            String s = array.stream().map(String::valueOf).collect(Collectors.joining(","));
            data.setCooperationType(",".concat(s).concat(","));
        }
        if (StringUtils.isNotBlank(operationType)) {
            List<Integer> array = JSONArray.parseArray(operationType, Integer.class);
            String s = array.stream().map(String::valueOf).collect(Collectors.joining(","));
            data.setOperationType(",".concat(s).concat(","));
        }
        if (StringUtils.isNotBlank(role)) {
            List<Integer> array = JSONArray.parseArray(role, Integer.class);
            String s = array.stream().map(String::valueOf).collect(Collectors.joining(","));
            data.setRole(",".concat(s).concat(","));
        }
    }


    @ApiOperation(value = "根据ID获取信息")
    @PostMapping(value = "/getById", produces = "application/json; charset=UTF-8")
    public R<Object> getById(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        Course course = courseService.getById(id);
        return R.ok(course);
    }


    @ApiOperation(value = "更新启用状态")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateEnabled(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "状态 0.禁用 1.启用") @RequestParam(value = "enabled") Integer enabled
    ) {
        courseService.updateEnabled(id, enabled);
        return R.ok();
    }


    @ApiOperation(value = "更新热门状态")
    @PostMapping(value = "/updateHotStatus", produces = "application/json; charset=UTF-8")
    public R<Object> updateHotStatus(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "热门状态 0.否 1.热门") @RequestParam(value = "hotStatus") Integer hotStatus
    ) {
        courseService.updateHotStatus(id, hotStatus);
        return R.ok();
    }


    @ApiOperation(value = "上移/下移")
    @PostMapping(value = "/upOrDown", produces = "application/json; charset=UTF-8")
    public R<Object> upOrDown(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "类型 1.上移 2.下移") @RequestParam(value = "type") Integer type
    ) {
        Course data = courseService.getById(id);
        if (data == null) return R.fail("获取失败");
        if (type.equals(1)) {
            // 上移
            Course preCourse = courseService.getLtOrderNum(data.getTypeId(), data.getOrderNum());
            if (preCourse == null) return R.fail("已在最前");
            // 和前一条记录的序号互换
            Integer prevOrderNum = preCourse.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            courseService.updateOrderNum(preCourse.getId(), curOrderNum);
            courseService.updateOrderNum(data.getId(), prevOrderNum);
        } else if (type.equals(2)) {
            // 下移
            Course backCourse = courseService.getGtOrderNum(data.getTypeId(), data.getOrderNum());
            if (backCourse == null) return R.fail("已在最后");
            // 和后一条记录的序号互换
            Integer backOrderNum = backCourse.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            courseService.updateOrderNum(backCourse.getId(), curOrderNum);
            courseService.updateOrderNum(data.getId(), backOrderNum);
        } else {
            return R.fail("类型错误");
        }
        return R.ok();
    }


    @ApiOperation(value = "删除")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        // 修改
        Course data = courseService.getById(id);
        if (null == data) return R.fail("获取失败");

        if (data.getType().equals(1)) {
            // 资料类型是视频
            long videoCnt = courseVideoService.getCourseIdCnt(id);
            if (videoCnt > 0) return R.fail("已上传视频，请先删除视频");

            long l = courseService.dropCourse(id);
            if (l <= 0) return R.fail("删除失败");
        } else {
            // 资料类型是下载资料
//            long l = courseService.dropCourse(id);
//            if (l <= 0) return R.fail("删除失败");
//            // 删除阿里云文件
//            deleteOssFile(data.getUrl());
            return R.fail("此功能已关闭");
        }

        return R.ok();
    }


    @ApiOperation(value = "新增/修改下载资料")
    @PostMapping(value = "/newDownload")
    public R<Object> newDownload(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "活动名称") @RequestParam(value = "name") String name,
            @ApiParam(value = "介绍内容") @RequestParam(value = "intro", required = false) String intro,
            @ApiParam(value = "主分类id") @RequestParam(value = "mainTypeId", required = false) Long mainTypeId,
            @ApiParam(value = "关联分类id") @RequestParam(value = "typeId") Long typeId,
            @ApiParam(value = "下载地址") @RequestParam(value = "url") String url
    ) {
        if (id == null || id <= 0) {
            // 新增
            CourseTypes mainType = courseTypesService.getById(mainTypeId);
            if (mainType == null) return R.fail("主分类获取失败");
            CourseTypes courseTypes = courseTypesService.getById(typeId);
            if (courseTypes == null) return R.fail("关联分类获取失败");
            if (!courseTypes.getLevelEnd().equals(1)) return R.fail("分类不是最后一层不能新增");

            // 获取最大的序号
            int maxOrderNum = courseService.getMaxShowOrder(typeId);

            Course data = new Course();
            data.setName(name);
            data.setIntro(intro);
            data.setMainTypeId(mainTypeId);
            data.setMainTypeName(mainType.getCourseTypeName());
            data.setTypeId(typeId);
            data.setTypeName(courseTypes.getCourseTypeName());
            data.setOrderNum(maxOrderNum + 1);
            data.setUrl(url);
            data.setDownloadNum(0);
            data.setType(mainType.getType());
            data.setEnabled(1);
            courseService.saveOrUpdate(data);
        } else {
            // 修改
            Course data = courseService.getById(id);
            if (data == null) return R.fail("获取失败");

            String exUrl = data.getUrl();

            if (name != null)
                data.setName(name);
            if (intro != null)
                data.setIntro(intro);
            if (url != null)
                data.setUrl(url);
            courseService.saveOrUpdate(data);

            // 上传的文件路径和原文件路径不一样，则删除原文件
            if (!exUrl.equals(url)) {
                // 删除阿里云文件
                deleteOssFile(exUrl);
            }

        }

        return R.ok();
    }


    @ApiOperation(value = "新增视频配套的下载资料")
    @PostMapping(value = "/newVideoDownload")
    public R<Object> newVideoDownload(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "下载地址") @RequestParam(value = "url") String url
    ) {
        // 修改
        Course data = courseService.getById(id);
        if (data == null)
            return R.fail("获取失败");

        String exUrl = data.getUrl();

        courseService.updateUrl(id, url);

        // 上传的文件路径和原文件路径不一样，则删除原文件
        if (StringUtils.isNotBlank(exUrl) && !exUrl.equals(url)) {
            // 删除阿里云文件
            deleteOssFile(exUrl);
        }

        return R.ok();
    }

    /**
     * 删除阿里云视频
     */
    private void deleteOssFile(String url) {
        if (AccountUtil.judgeProd(envi)) {
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.initOss();
            ossClientUtil.deleteFile(OSSClientUtil.privateBucket_subject, url);
        }
    }

}
